// 声明一个全局对象Namespace，用来注册命名空间
/* eslint-disable */
Namespace = new Object();


// 货币格式化
function currency(value, showSign, showUnit) {
    if (value != null) {
        var price;
        if (ErpSetting.priceRoundType == "roundHalfUp") {
            price = (Math.round(value * Math.pow(10, ErpSetting.priceScale)) / Math.pow(10, ErpSetting.priceScale)).toFixed(ErpSetting.priceScale);
        } else if (ErpSetting.priceRoundType == "roundUp") {
            price = (Math.ceil(value * Math.pow(10, ErpSetting.priceScale)) / Math.pow(10, ErpSetting.priceScale)).toFixed(ErpSetting.priceScale);
        } else {
            price = (Math.floor(value * Math.pow(10, ErpSetting.priceScale)) / Math.pow(10, ErpSetting.priceScale)).toFixed(ErpSetting.priceScale);
        }
        if (showSign) {
            price = ErpSetting.currencySign + price;
        }
        if (showUnit) {
            price += ErpSetting.currencyUnit;
        }
        return price;
    }
}

/**
 * 数字格式转换成千分位
 *@param{Object}num
 */
function format_number(num) {
    num = num + "";
    num = num.replace(/[ ]/g, ""); //去除空格  
    if (num == "") {
        return;
    }
    if (isNaN(num)) {
        return;
    }
    var reg = /(-?\d+)(\d{3})/;
    while (reg.test(num)) {
        num = num.replace(reg, "$1,$2");
    }
    return num;
}

function getProductImage(imagePath, type) {
    if (imagePath.indexOf("img.alicdn.com") >= 0) {
        return imagePath;
    } else {
        return imagePath.replace(".jpg", type);
    }
}

function format_thousands(num) {
    //1.先去除空格,判断是否空值和非数   
    num = num + "";
    num = num.replace(/[ ]/g, ""); //去除空格  
    if (num == "") {
        return;
    }
    if (isNaN(num)) {
        return;
    }
    num = parseFloat(num).toFixed(2);
    var index = num.indexOf(".");
    var intPart = num.substring(0, index);
    var pointPart = num.substring(index + 1, num.length);
    var reg = /(-?\d+)(\d{3})/;
    while (reg.test(intPart)) {
        intPart = intPart.replace(reg, "$1,$2");
    }
    num = intPart + "." + pointPart;

    return num;
}


function toFloat(num) {
    if (num == 0 || num == null)
        return $.erp.formZero;
    return parseFloat(num);
}

function formatToFloat(num) {
    if (num.indexOf(",") != -1)
        return num.replace(/,/g, '');
    return num;
}


function isNumber(val) {
    return typeof val === 'number' && isFinite(val);
}


(function ($) {

    $.getLocalTime = function (nS) {
        return new Date(parseInt(nS)).format("yyyy-MM-dd hh:mm");
    }
    $.getLocalDate = function (ns) {
        var newDate = new Date();
        newDate.setTime(ns);

        return newDate.format("yyyy-MM-dd");
    }
    $.getImageDomain = function () {
        return "http://yiigoo-tmp.oss-cn-shanghai.aliyuncs.com/";
    }
    $.clearInput = function () {
        $("#box-config").find("input").val("");
        $("#box-config").find("textarea").val("");
    }

    $.IsMoney = function (obj) {
        var v = $(obj).val();
        if (!isNaN(v)) {
            var regu = "^[0-9]+[\.][0-9]{0,2}$";
            var re = new RegExp(regu);
            if (!re.test(v))
                $(obj).val($.toFixed(v, 2));
        } else {
            $(obj).val(0);
        }
    };


    var zIndex = 100;

    $.startSpin = function (container) {
        var spinner = new Spinner();
        var $container = container;
        if (!$container) {
            $container = $("body");
        } else {
            $container.css("position", "relative");
        }

        var target = $("[role=spinner_container]", $container);
        if (target.length == 0) {
            var html = "<div role='spinner_container'></div>";
            $container.append(html);
        }
        target = $("[role=spinner_container]", $container).get(0);
        spinner.spin(target);
        return spinner;
    }


    $.dataTableLanguage = {
        "processing": "",
        "lengthMenu": "每页显示 _MENU_ 条",
        "zeroRecords": "没有数据！",
        "emptyTable": "没有数据！",
        "info": "",
        "infoEmpty": "",
        "infoFiltered": "数据表中共为 _MAX_ 条记录",
        "paginate": {
            "first": "首页",
            "previous": "<",
            "next": ">",
            "last": "末页",
            "redirect": "跳转至"

        }
    };

    $.dataTableSetting = function (setting) {
        var enableCheckbox = setting["enableCheckbox"];
        var checkboxColIndex = setting["checkboxColIndex"];

        if (enableCheckbox == undefined || enableCheckbox === "") {
            enableCheckbox = true;
        }
        if (!checkboxColIndex) {
            checkboxColIndex = 0;
        }
        var drawCheckbox = function ($dataTable, oSettings) {
            if (enableCheckbox && enableCheckbox == true) {
                var colIndex = checkboxColIndex;

                var len = $dataTable.closest(".dataTables_scrollBody").length;
                var $header = null;
                if (len == 0) {
                    $header = $dataTable.find("thead");
                } else {
                    $header = $dataTable.closest(".dataTables_scrollBody").prev().find("thead");
                }
                $header.find('th:eq(' + colIndex + ') input[type="checkbox"]').uniform();
                $dataTable.find('tbody tr:not([blank_row])').each(function (index, item) {
                    $(item).find('td:eq(' + colIndex + ') input[type="checkbox"]').uniform();
                });
                $dataTable.find('.checker span').each(function (index, item) {
                    $(item).append('<i class="glyph-icon icon-check"></i>');
                });
                $header.find('.checker span').each(function (index, item) {
                    $(item).append('<i class="glyph-icon icon-check"></i>');
                });
                //刷新全选按钮
                $header.find('th:eq(' + colIndex + ') input[type="checkbox"]').prop("checked", false);
                $.uniform.update($header.find('th:eq(' + colIndex + ') input[type="checkbox"]'));
                $header.off('click', 'th:eq(' + colIndex + ') input[type="checkbox"]');

                $header.on('click', 'th:eq(' + colIndex + ') input[type="checkbox"]', function () {
                    $.uniform.update($header.find('th:eq(' + colIndex + ') input[type="checkbox"]:enabled'));
                    var checked = this.checked;
                    $dataTable.find('tbody tr:not([blank_row])').each(function (index, item) {
                        $(item).find('td:eq(' + colIndex + ') input[type="checkbox"]:enabled').prop("checked", checked);
                        $.uniform.update($(item).find('td:eq(' + colIndex + ') input[type="checkbox"]'));
                    });
                });

                $dataTable.on('click', 'tbody tr:not([blank_row]) td div.checker input[type="checkbox"]:enabled', function () {
                    var len = 0,
                        slen = 0;
                    $dataTable.find('tbody tr:not([blank_row])').each(function (index, item) {
                        var checker = $(item).find('td:eq(' + colIndex + ') div.checker');
                        if (checker) {
                            len++;
                            var checked = $(checker).find('span.checked');
                            if (checked && checked.html()) {
                                slen++;
                            }

                        }
                    });

                    $header.find('th:eq(' + colIndex + ') input[type="checkbox"]').prop("checked", len == slen && len > 0 && this.checked ? true : false);
                    $.uniform.update($header.find('th:eq(' + colIndex + ') input[type="checkbox"]'));
                }); //全选反选
            }
        }

        var adjustCheckbox = function ($dataTable, oSettings) {
            var len = $dataTable.closest(".dataTables_scrollBody").length;
            var $header = null;
            var $tbody = null;
            if (len == 0) {
                $header = $dataTable.find("thead");
                $tbody = $dataTable.find("tbody");
            } else {
                $header = $dataTable.closest(".dataTables_scrollBody").prev().find("thead");
                $tbody = $dataTable.closest(".dataTables_scrollBody").prev().find("tbody");
            }
            if (enableCheckbox && enableCheckbox == true) {
                var colIndex = checkboxColIndex;
                if (oSettings.oFeatures.bAutoWidth == false) {
                    $header.find('th:eq(' + colIndex + ')').css({"width": "1%"});
                    $tbody.find('td:eq(' + colIndex + ')').css({"width": "1%"});

                } else {
                    $header.find('th:eq(' + colIndex + ')').css({"width": "20px"});
                    $tbody.find('td:eq(' + colIndex + ')').css({"width": "20px"});
                }
                $header.find('th:eq(' + colIndex + ')').css({"overflow": "hidden", "text-align": "center"});
                $tbody.find('td:eq(' + colIndex + ')').css({"overflow": "hidden", "text-align": "center"});

                $dataTable.find('tbody tr:not([blank_row])').each(function (index, item) {
                    $(this).find('td:eq(' + colIndex + ')').css({"padding": "0px 10px", "text-align": "center", "width": "20px"});
                });
                $dataTable.find('thead tr').each(function (index, item) {
                    $(this).find('th:eq(' + colIndex + ')').css({"padding": "0px 10px", "text-align": "center", "width": "20px", "vertical-align": "middle"});
                });

                $dataTable.DataTable().columns.adjust(); //调整列宽
            }
        }

        var fnDrawCallback = setting["fnDrawCallback"];
        var fnInitComplete = setting["fnInitComplete"];

        //函数的参数是固定，不能更改。  
        var retrieveData = function (sSource, aoData, fnCallback) {
            var $dataTable = $(this);
            var $spinner = null;
            var latestAjaxUrl = $dataTable.DataTable().ajax.url();
            var dataType = typeof setting["dataType"] == "undefined" ? "json" : "jsonp";
            if (latestAjaxUrl) {

                $.ajax({
                    type: "POST",
                    url: latestAjaxUrl,
                    dataType: dataType,
                    data: $.param(aoData, true),
                    beforeSend: function () {
                        var $spinnerContainer = $dataTable.closest("div.dataTables_wrapper");
                        $spinner = $.startSpin($spinnerContainer);
                        $dataTable.attr("load-status", "loading");
                    },
                    success: function (data) {
                        var responeData = data;
                        if (dataType == "jsonp")
                            responeData = data.extra;
                        $("#total").text(responeData.iTotalRecords);
                        $("#totalPrice").text(format_thousands(responeData.ext));

                        fnCallback(responeData);
                        if ($spinner)
                            $spinner.spin();
                        $dataTable.attr("load-status", "finish");
                    },
                    complete: function () {
                        if ($spinner)
                            $spinner.spin();
                        $dataTable.attr("load-status", "finish");
                    },
                    error: function () {
                        if ($spinner)
                            $spinner.spin();
                        $dataTable.attr("load-status", "finish");
                    }
                });
            }
        }

        var s = {
            "language": $.dataTableLanguage,
            "bDeferRender": true,
            "processing": false,
            "filter": false, // 去掉搜索框
            "lengthChange": true, // 每页显示数量
            "bStateSave": false,
            "bDestroy": true,
            "order": [
                [0, 'desc']
            ],
            "dom": "<'top'>rt<'bottom'pil><'clear'>", // 位置控制
            "fnServerData": retrieveData, //与后台交互获取数据的处理函数
            "fnDrawCallback": function (oSettings) {
                drawCheckbox($(this), oSettings);
                if (fnDrawCallback) {
                    fnDrawCallback.call(oSettings);
                }

                var $dataTable = $(this);
                adjustCheckbox($dataTable, oSettings);
                //补充空数据		        	
                var outerHeight = $dataTable.parent().height();
                var tableHeight = $dataTable.height();
                var whiteHeight = outerHeight - tableHeight;
                var trHeight = $dataTable.find(" tbody tr:last").height();
                var rowsNum = Math.floor(whiteHeight / trHeight);
                var lastTr = $dataTable.find(" tbody tr:last");
                if (lastTr.find("td:eq(0)").hasClass("dataTables_empty")) {
                    lastTr.removeClass("odd").removeClass("even").addClass("blank_row");
                    lastTr.attr("blank_row", "blank_row");
                }
                if (!isNumber(rowsNum)) { //避免无限死循环
                    rowsNum = 0;
                }
                for (var i = 0; i < rowsNum; i++) {
                    var ltr = $dataTable.find(" tbody tr:last").clone();
                    ltr.removeClass("odd").removeClass("even").addClass("blank_row");
                    ltr.attr("blank_row", "blank_row");
                    ltr.find("td").html("");
                    $dataTable.find(" tbody tr:last").after(ltr);
                }

                //添加金额千分位
                var tds = $dataTable.find("tbody tr:not('.blank_row') td");
                tds.each(function (i, item) {
                    var col = $(this).text();
                    //设置title
                    if (!col.startWith("<") && !col.endWith(">")) {
                        $(this).attr("title", col);
                    }
                    //设置金额的千分位
                    if ($(this).hasClass("format_thousands")) {
                        if (!isNaN(col)) { //如果是数字
                            $(this).text((format_thousands(col)));
                        }
                    }
                    //设置数字的千分位
                    if ($(this).hasClass("format_number")) {
                        if (!isNaN(col)) { //如果是数字
                            $(this).text((format_number(col)));
                        }
                    }
                });
            },
            "fnInitComplete": function (oSettings, json) {
                if (fnInitComplete) {
                    fnInitComplete.call(oSettings, json);
                }
                var $dataTable = $(this);
                adjustCheckbox($dataTable, oSettings);
            }
        };
        if (setting) {
            for (var attr in setting) {
                if ((attr + "") != "fnDrawCallback" &&
                    (attr + "") != "fnInitComplete") {
                    s[attr] = setting[attr];
                }
            }
        }
        return s;
    };

    $.alert = function (msg) {
        bootbox.dialog({
            message: msg,
            title: "操作提示",
            buttons: {
                success: {
                    label: "关闭",
                    className: "btn-default",
                    callback: function () {
                        $(".bootbox").modal("hide");
                    }
                }
            }
        });
    }
    $.confirm = function (msg, submit) {
        bootbox.dialog({
            message: msg,
            title: "操作提示",
            buttons: {
                cancel: {
                    label: "取消",
                    callback: function () {
                        $(".bootbox").modal("hide");
                    }
                },
                success: {
                    label: "确定",
                    className: "btn-success",
                    callback: submit
                }

            }
        });
    }


    $.getUrlParam = function (name) {
        var href = window.location.href;
        return $.extractParam(href, name);
    }

    $.extractParam = function (href, name) {
        var index = href.indexOf("?");
        if (index <= 0) return null;
        var r = href.substr(index + 1).split("&");
        if (r == null || r.length == 0) return null;
        r = [].concat(r);
        var result = [];
        for (var i = 0; i < r.length; i++) {
            var sTemp = r[i].split("=");
            if (sTemp[0] == name) {
                if (sTemp.length != 2) {
                    result.push(null);
                } else {
                    result.push(sTemp[1]);
                }
            }
        }
        if (result == null || result.length == 0) return null;
        if (result.length == 1) return decodeURI(result[0]);
        for (var i = 0; i < result.length; i++) {
            result[i] = decodeURI(result[i]);
        }
        return result;
    }
    $.getDomain = function () {
        return window.location.href.substr(0, window.location.href.indexOf("pages"));
    }

    //form 验证
    $.setFormValidation = function (form, rule) {

        if (!jQuery().bootstrapWizard) {
            return;
        }

        var wizform = $(form);
        /*-----------------------------------------------------------------------------------*/
        /*	Validate the form elements
        /*-----------------------------------------------------------------------------------*/
        wizform.validate({
            doNotHideMessage: true,
            errorClass: 'error-span',
            errorElement: 'span',
            rules: rule,
            highlight: function (element) {
                $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
            },

            unhighlight: function (element) {
                $(element).closest('.form-group').removeClass('has-error');
            },
            success: function (label) {
                label.addClass('valid').closest('.form-group').removeClass('has-error').addClass('has-success');

            }
        });


    };


    $.fn.form2json = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    }

    $.getSelectedList = function (that) {
        var result = [];
        $(that).find("tbody tr:not([blank_row]) div.checker span.checked :checkbox").each(function (index, item) {
            result.push($(item).val());
        })
        return result;
    }

    $.fn.getUnSelectedList = function () {
        var result = [];
        $(this).find("tbody tr:not([blank_row]) div.checker span").not(".checked").each(function (index, item) {
            result.push($(item).find(":checkbox").val());
        });
        return result;
    }


    // 检测登录
    $.checkLogin = function () {
        var result = false;
        $.ajax({
            url: $.getContextPath() + "/login/check.jhtml",
            type: "GET",
            dataType: "json",
            cache: false,
            async: false,
            success: function (data) {
                result = data;
            }
        });
        return result;
    }


    //重写 避免时间戳问题，缓存js
    $.getScript = function (url, callback, cache) {
        if (!cache) {
            cache = true;
        }
        $.ajax({type: 'GET', url: url, async: false, success: callback, dataType: 'script', ifModified: true, cache: cache});
    };

    /** 文件上传url,添加了csrf标记 */
    $.getUploadFileUrl = function () {
        return $.getContextPath() + "/os/file/uploadFile.do?" + parameter_csrf + "=" + token_csrf;
    };

    $.include = function (file) {
        var files = typeof file == "string" ? [file] : file;
        for (var i = 0; i < files.length; i++) {
            var name = files[i].replace(/^\s|\s$/g, "");
            var att = name.split('.');
            var ext = att[att.length - 1].toLowerCase();
            var isCSS = ext == "css";
            var tag = isCSS ? "link" : "script";
            var attr = isCSS ? " type='text/css' rel='stylesheet' " :
                " language='javascript' type='text/javascript' ";
            var link = (isCSS ? "href" : "src") + "='" + '' + name + "'";
            if ($(tag + "[" + link + "]").length == 0)
                $("head").append("<" + tag + attr + link + "></" + tag + ">");
        }
    }

    if (!$.erp) {
        $.erp = {};
    }

    $.erp.ajaxSubmit = function (opt) {
        //备份opt中error和success方法
        var fn = {
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            success: function (data, textStatus) {
            },
            beforeSend: function (XHR) {
            }
        }
        if (opt.error) {
            fn.error = opt.error;
        }
        if (opt.success) {
            fn.success = opt.success;
        }
        if (opt.beforeSend) {
            fn.beforeSend = opt.beforeSend;
        }

        var $spinner = null;
        //扩展增强处理
        var _opt = $.extend(opt, {
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //错误方法增强处理
                fn.error(XMLHttpRequest, textStatus, errorThrown);
                if (opt.viewer) {
                    $(":submit", opt.viewer).prop("disabled", false);
                }
                if ($spinner)
                    $spinner.spin();
            },
            success: function (data, textStatus) {
                //成功回调方法增强处理
                fn.success(data, textStatus);
                if (opt.viewer) {
                    $(":submit", opt.viewer).prop("disabled", false);
                }
                if ($spinner)
                    $spinner.spin();
            },
            beforeSend: function (XHR) {
                fn.beforeSend(XHR);
                if (opt.viewer) {
                    $(":submit", opt.viewer).prop("disabled", true);
                }
                //提交前回调方法
                $spinner = $.startSpin(opt.viewer);
            },
            complete: function (XHR, TS) {
                //请求完成后回调函数 (请求成功或失败之后均调用)。
                if (opt.viewer) {
                    $(":submit", opt.viewer).prop("disabled", false);
                }
                if ($spinner)
                    $spinner.spin();
            }
        });
        $.ajax(_opt);
    }

    $.erp.ajaxPost = function (url, param, successCallback, dataType, viewer) {
        $.erp.ajaxSubmit({
            url: url,
            type: "POST",
            data: param,
            dataType: dataType,
            success: successCallback,
            viewer: viewer
        });
    }

    $.setDefaultDate = function ($viewPanel) {
        var startDate = $('.bootstrap-datepicker[name=endDate]', $viewPanel).bsdatepicker({
            format: 'yyyy-mm-dd',
            onRender: function (date) {
                var nowTemp = new Date();
                var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
                return date.valueOf() < now.valueOf() ? 'disabled' : '';
            }
        });
        startDate.bsdatepicker("setValue", function () {
            var strDate = new Date();
            strDate.setDate(strDate.getDate() + 30);
            return strDate.format("yyyy-MM-dd")
        }());
        startDate.on('changeDate', function (ev) {
            startDate.bsdatepicker("hide");
        });
    }
    $.setDefaultDate = function ($viewPanel, name) {
        var startDate = $('.bootstrap-datepicker[name=' + name + ']', $viewPanel).bsdatepicker({
            format: 'yyyy-mm-dd',
            onRender: function (date) {
                var nowTemp = new Date();
                var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
                return date.valueOf() < now.valueOf() ? 'disabled' : '';
            }
        });
        startDate.bsdatepicker("setValue", function () {
            var strDate = new Date();
            strDate.setDate(strDate.getDate());
            return strDate.format("yyyy-MM-dd")
        }());
        startDate.on('changeDate', function (ev) {
            startDate.bsdatepicker("hide");
        });
    }
    //查询界面日期控件初始化
    $.initDate = function ($viewPanel, startDays, endDays, format = 'yyyy-mm-dd', viewMode = 0) {
        var startDate = $('.bootstrap-datepicker[name=startDate]', $viewPanel).bsdatepicker({
            format,
            autoclose: true,
            viewMode,
            onRender: function (date) {
                var endDateStr = $('.bootstrap-datepicker[name=endDate]', $viewPanel).val();
                if (!endDateStr) {
                    return '';
                }
                var ed = endDateStr.parseDate();
                if (!ed) return '';
                return date.valueOf() > ed.valueOf() ? 'disabled' : '';
            }
        });
        if (viewMode === 1) {
            startDate.bsdatepicker("setValue", startDays);
        } else {
            startDate.bsdatepicker("setValue", $.erp.startDate(startDays));
        }
        startDate.on('changeDate', function (ev) {
            if (endDate && endDate.date && ev.date.valueOf() >= endDate.date.valueOf()) {
                var newDate = new Date(ev.date)
                newDate.setDate(newDate.getDate());
                endDate.bsdatepicker("setValue", newDate);
            }
            endDate.bsdatepicker("fill");
            startDate.bsdatepicker("hide");
        });
        var endDate = $('.bootstrap-datepicker[name=endDate]', $viewPanel).bsdatepicker({
            format,
            autoclose: true,
            viewMode,
            onRender: function (date) {
                var startDateStr = $('.bootstrap-datepicker[name=startDate]', $viewPanel).val();

                if (!startDateStr) {
                    return '';
                }
                var sd = startDateStr.parseDate();
                if (!sd) return '';

                return date.valueOf() < sd.valueOf() ? 'disabled' : '';
            }
        });
        if (viewMode === 1) {
            endDate.bsdatepicker("setValue", endDays);
        } else {
            endDate.bsdatepicker("setValue", $.erp.endDate(endDays));
        }
        endDate.on('changeDate', function (ev) {
            if (startDate && startDate.date && ev.date.valueOf() < startDate.date.valueOf()) {
                var newDate = new Date(ev.date)
                newDate.setDate(newDate.getDate());
                startDate.bsdatepicker("setValue", newDate);
            }

            startDate.bsdatepicker("fill");
            endDate.bsdatepicker("hide");
        });
        endDate.on("input", function () {
            startDate.bsdatepicker("fill");
        });
        startDate.on("input", function () {
            endDate.bsdatepicker("fill");
        });
    }
    $.initDate2 = function ($viewPanel, startDays, endDays, startName, endName, format = 'yyyy-mm-dd', viewMode = 0) {
        var startDate = $('.bootstrap-datepicker[name=' + startName + ']', $viewPanel).bsdatepicker({
            format,
            autoclose: true,
            viewMode,
            onRender: function (date) {
                var endDateStr = $('.bootstrap-datepicker[name=' + endName + ']', $viewPanel).val();
                if (!endDateStr) {
                    return '';
                }
                var ed = endDateStr.parseDate();
                if (!ed) return '';
                return date.valueOf() > ed.valueOf() ? 'disabled' : '';
            }
        });
        if (viewMode === 1) {
            startDate.bsdatepicker("setValue", startDays);
        } else {
            startDate.bsdatepicker("setValue", $.erp.startDate(startDays));
        }
        startDate.on('changeDate', function (ev) {
            if (endDate && endDate.date && ev.date.valueOf() >= endDate.date.valueOf()) {
                var newDate = new Date(ev.date)
                newDate.setDate(newDate.getDate());
                endDate.bsdatepicker("setValue", newDate);
            }
            endDate.bsdatepicker("fill");
            startDate.bsdatepicker("hide");
        });
        var endDate = $('.bootstrap-datepicker[name=' + endName + ']', $viewPanel).bsdatepicker({
            format,
            autoclose: true,
            viewMode,
            onRender: function (date) {
                var startDateStr = $('.bootstrap-datepicker[name=' + startName + ']', $viewPanel).val();

                if (!startDateStr) {
                    return '';
                }
                var sd = startDateStr.parseDate();
                if (!sd) return '';

                return date.valueOf() < sd.valueOf() ? 'disabled' : '';
            }
        });
        if (viewMode === 1) {
            endDate.bsdatepicker("setValue", endDays);
        } else {
            endDate.bsdatepicker("setValue", $.erp.endDate(endDays));
        }
        endDate.on('changeDate', function (ev) {
            if (startDate && startDate.date && ev.date.valueOf() < startDate.date.valueOf()) {
                var newDate = new Date(ev.date)
                newDate.setDate(newDate.getDate());
                startDate.bsdatepicker("setValue", newDate);
            }

            startDate.bsdatepicker("fill");
            endDate.bsdatepicker("hide");
        });
        endDate.on("input", function () {
            startDate.bsdatepicker("fill");
        });
        startDate.on("input", function () {
            endDate.bsdatepicker("fill");
        });
    }
    $.nowDate = function () {
        var strDate = new Date();
        return strDate.format("yyyy-MM-dd");
    }

    //获取开始日期和结束日期	
    $.erp.startDate = function (days) {
        var strDate = new Date();
        strDate.setDate(strDate.getDate() + days);
        return strDate.format("yyyy-MM-dd");
    }
    $.erp.endDate = function (days) {
        var strDate = new Date();
        strDate.setDate(strDate.getDate() + days);
        return strDate.format("yyyy-MM-dd");
    }
    $.dateAdd = function (strDate) {
        if (strDate != "") {
            var tempDate = new Date(strDate.replace(/-/g, '/'));
            tempDate.setDate(tempDate.getDate() + 1);
            return tempDate.format("yyyy-MM-dd");
        }
        return "";
    }


    //只能输入整数
    $.IsNum = function (e) {
        var k = window.event ? e.keyCode : e.which;
        if (((k >= 48) && (k <= 57)) || k == 8 || k == 0) {
        } else {
            if (window.event) {
                window.event.returnValue = false;
            } else {
                e.preventDefault(); //for firefox 
            }
        }

    };
    $.IsNaN = function (obj) {
        if (isNaN($(obj).val()))
            $(obj).val(1);
    };

    //输入小数
    $.IsDecimal = function (e) {
        var k = window.event ? e.keyCode : e.which;
        if (((k >= 48) && (k <= 57)) || k == 8 || k == 0 || k == 46) {
        } else {
            if (window.event) {
                window.event.returnValue = false;
            } else {
                e.preventDefault(); //for firefox 
            }
        }
    }


    $.toFixed = function (number, precision) {
        var b = 1;
        if (isNaN(number)) return number;
        if (number < 0) b = -1;
        var multiplier = Math.pow(10, precision);
        return Math.round(Math.abs(number) * multiplier) / multiplier * b;
    };


    $.createLocalImageURL = function (key) {
        if (!key) return;
        var contextPath = $.getContextPath();
        if (!contextPath.endWith("/")) {
            contextPath += "/";
        }
        if (key.startWith("/")) {
            key = key.substring(1);
        }
        return contextPath + key;
    }

    $.erp.setWidth = function ($viewPanel) {

        $viewPanel.find(".table thead th").each(function (index) {

            var _this = $(this).width();
            $viewPanel.find(".justbottom div:eq(" + index + ")").width(_this);
        });
    };

    $.erp.registerSearch = function () {
        document.onkeydown = function (e) {
            var ev = document.all ? window.event : e;
            if (ev.keyCode == 13) {
                var formId = $("#page-content-body .show div:eq(0)").attr("id");
                $("#" + formId).find(".search").trigger("click");
            }
        }
    };

    $.erp.getUrlParms = function (query) {
        var args = new Object();
        if (!query) return args;
        var strs = query.split("?");
        if (strs.length > 1) {
            query = strs[1];
        }
        var pairs = query.split("&"); // 在逗号处断开

        for (var i = 0; i < pairs.length; i++) {
            var pos = pairs[i].indexOf('='); // 查找name=value
            if (pos == -1)
                continue; // 如果没有找到就跳过
            var argname = pairs[i].substring(0, pos); // 提取name
            var value = pairs[i].substring(pos + 1); // 提取value
            if (args[argname]) {
                if ($.isArray(args[argname])) {
                    args[argname].push(unescape(value));
                } else {
                    args[argname] = [args[argname], unescape(value)]; // 存为属性
                }
            } else {
                args[argname] = unescape(value); // 存为属性
            }
        }

        return args;
    }


    $.erp.formZero = function () {
        var zero = 0;
        return zero.toFixed(2);
    }


    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    $.fn.serializeTable = function () {
        var table = this;
        var arr = new Array();
        table.find("tbody tr:not('.blank_row')").each(function () {
            var obj = {};
            var tds = $(this).find("td");
            tds.each(function () {
                var clz = $.trim($(this).attr("class")).split(" ")[0];
                if (clz != null && clz != "") {
                    var content = $(this).html();

                    if (content.startWith("<input")) {
                        obj[clz] = $(this).find("input").val();
                    } else {
                        obj[clz] = $(this).html();
                    }
                }
            });
            arr.push(obj);
        });

        return arr;
    }

    $.fn.serializeTableTr = function () {
        var tr = this;
        var tds = tr.find("td");
        var obj = {};
        tds.each(function () {
            var clz = $.trim($(this).attr("class")).split(" ")[0];
            if (clz != null && clz != "") {
                obj[clz] = $(this).html();
            }
        });
        return obj;
    };


    $.getTimeStamp = function (nl) {
        var nowTimeStamp = new Date();
        return nowTimeStamp.diffDays(new Date(parseInt(nl)))
    }


})(jQuery);

$.ajaxSetup({
    timeout: 60000,
    cache: false,


});


//数组
Array.prototype.clear = function () { //用于清空数组
    this.length = 0;
}
Array.prototype.indexOf = function (obj) {
    for (var i = 0, imax = this.length; i < imax; i++) {
        if (this[i] === obj) {
            return i;
        }
    }
    return -1;
}
/*Array.prototype.contains = function(obj) {//判断数据项是否在该数组中

    return this.indexOf(obj) !== -1;
}*/
Array.prototype.insertAt = function (index, obj) { //把数据项添加到指定的位置
    if (index < 0)
        index = 0;
    if (index > this.length)
        index = this.length;
    this.length++;
    for (var i = this.length - 1; i > index; i--) {
        this[i] = this[i - 1];
    }
    this[index] = obj;
}
Array.prototype.last = function () {
    return this[this.length - 1];
}
Array.prototype.removeAt = function (index) {
    if (index < 0 || index >= this.length)
        return;
    var item = this[index];
    for (var i = index, imax = this.length - 2; i < imax; i++) {
        this[i] = this[i + 1];
    }
}
Array.prototype.remove = function (val, obj) {
    var index = -1;
    for (var i = 0, imax = obj.length; i < imax; i++) {
        if (obj[i] == val) {
            index = i;
        }
    }

    if (index > -1) {
        this.splice(index, 1);
    }
};

String.prototype.replaceAll = function (reallyDo, replaceWith, ignoreCase) {
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")), replaceWith);
    } else {
        return this.replace(reallyDo, replaceWith);
    }
}
String.prototype.endWith = function (s) {
    if (s == null || s == "" || this.length == 0 || s.length > this.length)
        return false;
    if (this.substring(this.length - s.length) == s)
        return true;
    else
        return false;
    return true;
}
String.prototype.startWith = function (s) {
    if (s == null || s == "" || this.length == 0 || s.length > this.length)
        return false;
    if (this.substr(0, s.length) == s)
        return true;
    else
        return false;
    return true;
}
String.prototype.encodeURI = function () {
    return encodeURI(this).replace(/\+/g, "%2B");
}
String.prototype.parseDate = function () {
    var str = this;
    if (!str) return null;

    var tempStrs = str.split(" ");

    var dateStrs = tempStrs[0].split("-");
    var year = parseInt(dateStrs[0], 10);
    var month = parseInt(dateStrs[1], 10) - 1;
    var day = parseInt(dateStrs[2], 10);

    var timeStrs = 0;
    var hour = 0;
    var minute = 0;
    var second = 0;

    if (tempStrs.length == 2) {
        timeStrs = tempStrs[1].split("-");
        hour = parseInt(timeStrs[0], 10);
        minute = parseInt(timeStrs[1], 10) - 1;
        second = parseInt(timeStrs[2], 10);
    }

    var date = new Date(year, month, day, hour, minute, second);
    return date;
}


var formatThousands = function () {
    var num = this + "";
    num = num + "";
    num = num.replace(/[ ]/g, ""); //去除空格  
    if (num == "") {
        return;
    }
    if (isNaN(num)) {
        return;
    }
    num = parseFloat(num).toFixed(2);
    var index = num.indexOf(".");
    var intPart = num.substring(0, index);
    var pointPart = num.substring(index + 1, num.length);
    var reg = /(-?\d+)(\d{3})/;
    while (reg.test(intPart)) {
        intPart = intPart.replace(reg, "$1,$2");
    }
    num = intPart + "." + pointPart;

    return num;
}


function formatNumber() {
    num = this + "";
    num = num.replace(/[ ]/g, ""); //去除空格  
    if (num == "") {
        return;
    }
    if (isNaN(num)) {
        return;
    }
    var reg = /(-?\d+)(\d{3})/;
    while (reg.test(num)) {
        num = num.replace(reg, "$1,$2");
    }
    return num;
}

//格式化数字(有小数)
String.prototype.formatThousands = formatThousands;
Number.prototype.formatThousands = formatThousands;
//格式化数字(没有小数)
String.prototype.formatNumber = formatNumber;
Number.prototype.formatNumber = formatNumber;

String.prototype.thousandToFloat = function () {
    if (this.indexOf(",") != -1)
        return this.replace(/,/g, '');
    return this;
};


Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) :
                (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
Date.prototype.diffDays = function (date) {
    var ms = this.getTime() - date.getTime() //时间差的毫秒数
    //计算出相差天数
    return Math.floor(ms / (24 * 3600 * 1000));
}

/**
 * 本月第一天
 */
function monthFirstDay() {
    var Nowdate = new Date();
    var MonthFirstDay = new Date(Nowdate.getFullYear(), Nowdate.getMonth(), 1);
    return MonthFirstDay.format('yyyy-MM-dd')
}

/**
 * 本月最后一天
 */
function monthLastDay() {
    var Nowdate = new Date();
    var MonthNextFirstDay = new Date(Nowdate.getFullYear(), Nowdate.getMonth() + 1, 1);
    var MonthLastDay = new Date(MonthNextFirstDay - 86400000);
    return MonthLastDay.format('yyyy-MM-dd')
}

/**
 * 上月第一天
 */
function preMonthFirstDay() {
    var Nowdate = new Date();
    var MonthFirstDay = new Date(Nowdate.getFullYear(), Nowdate.getMonth() - 1, 1);
    return MonthFirstDay.format('yyyy-MM-dd')
}

/**
 * 上月最后一天
 */
function preMonthLastDay() {
    var Nowdate = new Date();
    var MonthNextFirstDay = new Date(Nowdate.getFullYear(), Nowdate.getMonth(), 1);
    var MonthLastDay = new Date(MonthNextFirstDay - 86400000);
    return MonthLastDay.format('yyyy-MM-dd')
}

var todayStart = function () {
    return new Date().format("yyyy-MM-dd");
}
var todayEnd = function () {
    var Nowdate = new Date();
    return new Date(Nowdate.getFullYear(), Nowdate.getMonth(), Nowdate.getDate() + 1).format("yyyy-MM-dd");
}

var yesterdayStart = function () {
    var Nowdate = new Date();
    return new Date(Nowdate.getFullYear(), Nowdate.getMonth(), Nowdate.getDate() - 1).format("yyyy-MM-dd");
}
var yesterdayEnd = function () {
    var Nowdate = new Date();
    return new Date(Nowdate.getFullYear(), Nowdate.getMonth(), Nowdate.getDate()).format("yyyy-MM-dd");
}
var addDate = function (date, days) {
    var d = new Date(date);
    d.setDate(d.getDate() + days);
    var month = d.getMonth() + 1;
    var day = d.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    var val = d.getFullYear() + "-" + month + "-" + day;
    return val;
}

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};